#!/bin/bash
# NOTE: sh 报错: "[[: not found" ，所以替换为 bash

CC=$1
CFLAGS=
AC="tools/config.c"
AOUT="tools/config.out"

# noop() { echo > /dev/null;}

if [ "$1" = "tcc" ]; then
  TEST_CONFIG="$CC $CFLAGS -run $AC"
fi

TARGET=`$CC -v 2>&1 | sed -e "/Target:/b" -e "/--target=/b" -e d | sed "s/.* --target=//; s/Target: //; s/ .*//" | head -1`
if [ "$1" = "tcc" ]; then
  # TARGET=`$CC -v 2>&1`
  TARGET=`uname -m`-`uname -s``uname -r`
fi
MINGW_GCC=`echo "$TARGET" | sed "/mingw/!d"`
if [ "$MINGW_GCC" = "" ]; then
  MINGW=0
else
  MINGW=1
fi
JIT_X86=`echo "$TARGET" | sed "/86/!d"`
JIT_PPC=`echo "$TARGET" | sed "/powerpc/!d"`

if [ "$2" = "mingw" ]; then
  if [ $MINGW -eq 0 ]; then
    echo "0"
  else
    echo "1"
  fi
elif [ "$2" = "version" ]; then
  cat core/potion.h | sed "/POTION_VERSION/!d; s/\\\"$//; s/.*\\\"//"
elif [ "$2" = "strip" ]; then
  if [ $MINGW -eq 0 ]; then
  # if [[ $MINGW -eq 0 && "$1" -ne "tcc" ]]; then
    echo "strip -x"
  else
    echo "ls"
  fi
elif [ "$2" = "target" ]; then
  if [ "$JIT_X86$MINGW_GCC" != "" ]; then
    echo "x86"
  elif [ "$JIT_PPC" != "" ]; then
    echo "ppc"
  fi
else
  if [ "$JIT_X86$MINGW_GCC" != "" ]; then
    # echo "#define POTION_TARGET     x86"
    echo "#define POTION_X86"
  elif [ "$JIT_PPC" != "" ]; then
    # echo "#define POTION_TARGET     ppc"
    echo "#define POTION_PPC"
  fi
  echo "#define POTION_PLATFORM   \"$TARGET\""
  echo "#define POTION_WIN32      $MINGW"
  echo

  if [ $MINGW -eq 0 ]; then
    if [ "$1" = "tcc" ]; then
      $CC $CFLAGS -run $AC
    else
      $CC $CFLAGS $AC -o $AOUT && $AOUT && rm -f $AOUT
    fi
  else
    # hard coded win32 values
    echo "#define PN_SIZE_T         4"
    echo "#define LONG_SIZE_T       4"
    echo "#define DOUBLE_SIZE_T     8"
    echo "#define INT_SIZE_T        4"
    echo "#define SHORT_SIZE_T      2"
    echo "#define CHAR_SIZE_T       1"
    echo "#define LONGLONG_SIZE_T   8"
    echo "#define PN_LITTLE_ENDIAN  1"
    echo "#define POTION_PAGESIZE   4096"
    echo "#define POTION_STACK_DIR  -1"
    # echo "#define POTION_ARGS_DIR   1"
  fi
fi
